/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yatb.trac.pojo.condition;

import com.yatb.trac.pojo.Progetti;
import com.yatb.trac.pojo.Utenti;
import com.yatb.trac.util.SQLCondition;
import com.yatb.trac.util.StatoConstant;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author edoardo
 */
public class TicketsFinderByProgettiUtenteAndStatoApertoInCarico implements SQLCondition {

    private Utenti utente;

    public TicketsFinderByProgettiUtenteAndStatoApertoInCarico(Utenti utente){
        this.utente=utente;
    }

    public Criterion create(Object... params) {
        Criterion result = getProgettiCriterions();
        result = Restrictions.and(result, Restrictions.or(Restrictions.eq("stati.idStato", StatoConstant.APERTO.getIdStato()), Restrictions.eq("stati.idStato", StatoConstant.IN_CARICO.getIdStato())));
        result = Restrictions.and(result,Restrictions.eq("utentiByIdUtente.idUtente",utente.getIdUtente()));
        return result;
    }

	protected Criterion getProgettiCriterions() {
		Set<Progetti> progetti = utente.getProgettis();
        List<Criterion> criterions = new ArrayList<Criterion>();
        Criterion result = null;
        for (Iterator<Progetti> it = progetti.iterator(); it.hasNext();) {
            Progetti p = it.next();
            criterions.add(Restrictions.eq("idProgetto", p.getIdProgetto()));
        }
        if (criterions.size() > 1) {
            for (int i = 0; i < criterions.size(); i++) {
                if (result == null) {
                    Criterion a = criterions.get(i);
                    Criterion b = criterions.get(i + 1);
                    result = Restrictions.or(a, b);

                } else {
                    result = Restrictions.or(result, criterions.get(i));

                }
            }
        } else {
            result = criterions.get(0);
        }
		return result;
	}
}
